
/****************************************************************************/
/*Copyright (c) 2011, Florent DEVILLE.                                      */
/*All rights reserved.                                                      */
/*                                                                          */
/*Redistribution and use in source and binary forms, with or without        */
/*modification, are permitted provided that the following conditions        */
/*are met:                                                                  */
/*                                                                          */
/* - Redistributions of source code must retain the above copyright         */
/*notice, this list of conditions and the following disclaimer.             */
/* - Redistributions in binary form must reproduce the above                */
/*copyright notice, this list of conditions and the following               */
/*disclaimer in the documentation and/or other materials provided           */
/*with the distribution.                                                    */
/* - The names of its contributors cannot be used to endorse or promote     */
/*products derived from this software without specific prior written        */
/*permission.                                                               */
/* - The source code cannot be used for commercial purposes without         */ 
/*its contributors' permission.                                             */
/*                                                                          */
/*THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS       */
/*"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT         */
/*LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS         */
/*FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE            */
/*COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT,       */
/*INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING,      */
/*BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;          */
/*LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER          */
/*CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT        */
/*LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN         */
/*ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE           */
/*POSSIBILITY OF SUCH DAMAGE.                                               */
/****************************************************************************/

#include "Plug.h"

#include "DirectionalLight.h"
#include "PointLight.h"
#include "SpotLight.h"

#include "GeoSphere.h"
#include "GeoBox.h"
#include "GeoCone.h"
#include "GeoCylinder.h"
#include "GeoTorus.h"
#include "GeoMesh.h"

#include "Material.h"
#include "CMaterial.h"

#include "Scene.h"
#include "MaLoRTLib.h"

//add the lights to the raytracer scene
void Plug::plugLights()
{
	for(QLinkedList<GUIILight*>::iterator i = SCENE._lights.begin(); i != SCENE._lights.end(); i++)
	{
		if ((*i)->getType() == LT_DIRECTIONAL)
		{
			DirectionalLight* light = (DirectionalLight*)(*i);
			//get the light color
			Material m = light->getMaterial();
			float* d = m.getDiffuse();
			CColor c(d[0], d[1], d[2], 1);

			//create a directional light
			CVector3f direction = light->getDirection();
			CDirectionalLight* newLight = new CDirectionalLight(c, direction);

			//add the light to the raytracer scene.
			RTSCENE.addLight(newLight);
		}
		else if ((*i)->getType() == LT_SPOT)
		{
			SpotLight* light = (SpotLight*)(*i);

			//get the light
			Material m = light->getMaterial();
			float * d = m.getDiffuse();
			CColor c(d[0], d[1], d[2], 1);

			//calculate cutOff
			float cutOff = light->getCutOff() * 3.14f / 180;
			
			//calculate direction
			CVector3f direction = light->calculateDirection();

			//calculate position
			CVector3f position = light->getTranslate();

			//create a spot light
			CSpotLight* newLight = new CSpotLight(c, position, direction,
				cutOff, 1, light->getAttenuation());

			//add the spot light
			RTSCENE.addLight(newLight);
		}
		else if ((*i)->getType() == LT_POINT)
		{
			PointLight* light = (PointLight*)(*i);

			//get the light
			Material m = light->getMaterial();
			float * d = m.getDiffuse();
			CColor c(d[0], d[1], d[2], 1);

			//get position
			CVector3f position = light->getTranslate();

			//create a new point light
			CPointLight* newLight = new CPointLight(position, c, light->getAttenuation());

			//add the light to the scene
			RTSCENE.addLight(newLight);
		}
	}
}

//add the primitives to the raytracer
void Plug::plugPrimitives()
{
	for (QLinkedList<Geometry*>::iterator i = SCENE._primitives.begin(); i != SCENE._primitives.end(); i++)
	{
		//sphere
		if ((*i)->getType() == GT_SPHERE)
		{
			//the the sphere object
			GeoSphere* p = (GeoSphere*)(*i);

			//create the raytracer primitive
			CPrimSphere* newP = new CPrimSphere(p->getRadius());
			newP->setWorldMatrix(p->getWorldMatrix());

			//create the material
			Material m	= p->getMaterial();
			CMaterial* newM = plugMaterial(&m);
			newP->setMaterial(newM);

			//add the primitive to the raytracer scene
			RTSCENE.addPrimitive(newP);
		}
		else if ((*i)->getType() == GT_BOX) //Box
		{
			//the the sphere object
			GeoBox* p = (GeoBox*)(*i);

			//create the raytracer primitive
			CPrimBox* newP = new CPrimBox(p->getWidth(), p->getHeight(), p->getDepth());
			newP->setWorldMatrix(p->getWorldMatrix());

			//create the material
			Material m = p->getMaterial();
			CMaterial* newM = plugMaterial(&m);

			newP->setMaterial(newM);

			//add the primitive to the raytracer scene
			RTSCENE.addPrimitive(newP);
		}
		else if ((*i)->getType() == GT_CYLINDER) //cylinder
		{
			//the the sphere object
			GeoCylinder* p = (GeoCylinder*)(*i);

			//create the raytracer primitive
			CPrimCylinder* newP = new CPrimCylinder(p->getRadius(), p->getHeight());
			newP->setWorldMatrix(p->getWorldMatrix());

			//create the material
			Material m = p->getMaterial();
			CMaterial* newM = plugMaterial(&m);

			newP->setMaterial(newM);

			//add the primitive to the raytracer scene
			RTSCENE.addPrimitive(newP);
		}
		else if ((*i)->getType() == GT_CONE) //cone
		{
			//the the sphere object
			GeoCone* p = (GeoCone*)(*i);

			//create the raytracer primitive
			CPrimCone* newP = new CPrimCone(p->getRadius(), p->getHeight());
			newP->setWorldMatrix(p->getWorldMatrix());

			//create the material
			Material m = p->getMaterial();
			CMaterial* newM = plugMaterial(&m);

			newP->setMaterial(newM);

			//add the primitive to the raytracer scene
			RTSCENE.addPrimitive(newP);
		}
		else if ((*i)->getType() == GT_TORUS) //torus
		{
			//the the sphere object
			GeoTorus* p = (GeoTorus*)(*i);

			//create the raytracer primitive
			CPrimTore* newP = new CPrimTore(p->getBigRadius(), p->getSmallRadius());
			newP->setWorldMatrix(p->getWorldMatrix());

			//create the material
			Material m = p->getMaterial();
			CMaterial* newM = plugMaterial(&m);

			newP->setMaterial(newM);

			//add the primitive to the raytracer scene
			RTSCENE.addPrimitive(newP);
		}
		else if((*i)->getType() == GT_MESH)
		{
			plugMesh((GeoMesh*)(*i));
		}
	}
}

//set the screen ratio
void Plug::plugScreen(float ratioWidth, float ratioHeight, float fov)
{
	RAYTRACER.setScreen(ratioWidth, ratioHeight, fov);
}

//set the picture resolution
void Plug::plugResolution(int width, int height)
{
	RAYTRACER.setResolution(width, height);
}

//set the camera
void Plug::plugCamera(const CVector3f& eye, const CVector3f at, const CVector3f up)
{
	RAYTRACER.setViewer(eye, at, up);
}

//set oversamping
void Plug::plugOversampling(CRayTracer::OVERSAMPLING ovs)
{
	RAYTRACER.setOverSampling(ovs);
}

//plug a material
CMaterial* Plug::plugMaterial(Material* m)
{
	//create the material
	CMaterial* newM = new CMaterial();

	//ambient
	float* a = m->getAmbient();
	newM->setAmbient(RTVector4f(a[0], a[1], a[2], 1));

	//diffuse
	float* d = m->getDiffuse();
	newM->setDiffuse(RTVector4f(d[0], d[1], d[2], 1));

	//specular
	float* s = m->getSpecular();
	newM->setSpecular(RTVector4f(s[0], s[1], s[2], 1));

	//shininess
	newM->m_shininess = m->getShininess();

	//texture
	if (m->getTexture() != -1)
	{
		CTexture* newTexture = new CTexture();
		newTexture->loadTexture(m->getTextureFilename());
		RTSCENE.addFileTexture(newTexture);

		newM->setAmbient(newTexture);
		newM->setDiffuse(newTexture);
	}

	newM->m_reflect = RTVector4f(0, 0, 0, 1);
	newM->m_refractionIndex = 0;
	//newM->m_transparancyCoef = 0;

	//add the material to the scene
	string matName = "MAT";
	int iVersionNumber = 0;
	string completeName;
	do
	{
		char n[255];
		_itoa_s(iVersionNumber, n, 10);
		string versionNumber = n;
		completeName = matName + versionNumber;
		iVersionNumber++;
	}
	while (!RTSCENE.addMaterial(newM, completeName));


	return newM;
}

//set the global ambient light
void Plug::plugGlobalAmbientLight()
{
	float* gal = SCENE.getGlobalAmbientLight();
	RTSCENE.setGlobalAmbientLight(CColor(gal[0], gal[1], gal[2], 1));
}

//plug a mesh
void Plug::plugMesh(GeoMesh* mesh)
{
	//calculate smooth normals
	mesh->calculateNormalPerVertex();

	//create the material
	Material m = mesh->getMaterial();
	CMaterial* newM = plugMaterial(&m);

	//for each triangle
	int nbTriangles = mesh->getTrianglesCount();
	for(int idTriangle = 0; idTriangle <nbTriangles; idTriangle++)
	{
		int idIndexBuffer = idTriangle * 3;
		int idVertexBuffer0 = mesh->_indexBuffer[idIndexBuffer];
		int idVertexBuffer1 = mesh->_indexBuffer[idIndexBuffer+1];
		int idVertexBuffer2 = mesh->_indexBuffer[idIndexBuffer+2];

		CPrimTriangle* newTriangle = new CPrimTriangle();
		newTriangle->addVertex(mesh->_vertexBuffer[idVertexBuffer0]._position, 0);
		newTriangle->addVertex(mesh->_vertexBuffer[idVertexBuffer1]._position, 1);
		newTriangle->addVertex(mesh->_vertexBuffer[idVertexBuffer2]._position, 2);
		newTriangle->addUV(mesh->_uvMapBuffer[idIndexBuffer], 0);
		newTriangle->addUV(mesh->_uvMapBuffer[idIndexBuffer+1], 1);
		newTriangle->addUV(mesh->_uvMapBuffer[idIndexBuffer+2], 2);

		//newTriangle->computeNormal();
		newTriangle->setNormal(mesh->_normalPerTriangleBuffer[idTriangle]);
	
		newTriangle->setMaterial(newM);
		newTriangle->preCompute();

		newTriangle->setWorldMatrix(mesh->getWorldMatrix());

		//add the primitive to the raytracer scene
		RTSCENE.addPrimitive(newTriangle);
	}

	
}